const encryption = require("../Models/encryption");
const Admin = require("../Models/admin");
const fs = require('fs');
const {join} = require('path');
const xlsx = require("../Models/readExcel");
const addUser = require('./userManagement');
const addQuestion = require('./questionManagement');

exports.login = async ctx => {
    // 用户登录 post 发过来的数据
    const admin = ctx.request.body;
    const adminName = admin.username;
    const password = encryption(admin.password);

    // 去数据库 admins 查询 adminName 是否存在
    await new Promise((resolve, reject) => {
        Admin.find({adminName}, (err, data) => {
            // 判断查找是否出错
            if (err) return reject(err);
            // 判断返回数据是否为空，空则用户不存在
            if (data.length !== 0) {
                console.log(data)
                resolve(data);
            }else {
                resolve(false);
            }
        })
    })
        .then( data => {
            if (data) {
                if (JSON.parse(JSON.stringify(data[0])).password === password) {
                    ctx.cookies.set("adminName", adminName, {
                        domain: 'localhost',
                        path: '/',
                        maxAge: 36e5,
                        httpOnly: true,
                        overwrite: false
                    });

                    ctx.body = {
                        status: 200,
                        msg: "登录成功，即将跳转"
                    };
                }else {
                    ctx.body = {
                        status: 404,
                        msg: "密码错误"
                    }
                }
            }else {
                ctx.body = {
                    status: 404,
                    msg: "用户不存在"
                }
            }
        })
        .catch( err => {
            console.log(err);
            ctx.body = {
                status: 404,
                msg: "未知错误"
            }
        })
};

// 确定管理员的状态  保持管理员的状态
exports.keepLog = async (ctx, next) => {
    console.log(ctx.session.isNew)
    if (ctx.session.isNew) {// session没有
        if (ctx.cookies.get("adminName")) {
            ctx.session = {
                adminName: ctx.cookies.get('adminName')
            }
        }
    }
    await next()
};

// 用户退出中间件
exports.logout = async ctx => {
    ctx.session = null;
    ctx.cookies.set("username", null, {
        maxAge: 0
    });
    // 在后台做重定向
    ctx.redirect("/")
};

exports.userUpload = async ctx => {
    const filename = fs.readdirSync(join( __dirname, '../public/xlsx'));
    if (filename.length !== 0) {
        let user = xlsx.user( join( __dirname, `../public/xlsx/${filename[0]}`) );
        await addUser.addUserPlus(user)
            .then(res => {
                let errMsg = [];
                if (res) {
                    let errs = res.writeErrors;
                    if (errs) {
                        for (let WriteError in errs) {
                            errMsg.push({
                                name: errs[WriteError].err.op.name,
                                username: errs[WriteError].err.op.username
                            });
                        }
                    }else {
                        errs = res;
                        errMsg.push({
                            name: errs.op.name,
                            username: errs.op.username
                        })
                    }
                }
                // 数组去重
                let obj = {};
                errMsg = errMsg.reduce(function (item, next) {
                    obj[next.username] ? '' : obj[next.username] = true && item.push(next);
                    return item;
                }, []);
                console.log(errMsg)
                ctx.body = {
                    status: 200,
                    msg: '上传成功',
                    errMsg
                }
            }).catch(err => {
                console.log(err)
            });
    }else {
        ctx.body = {
            status: 400,
            msg: '上传失败，请重试'
        }
    }
};

exports.questionUpload = async ctx => {
    const filename = fs.readdirSync(join( __dirname, '../public/xlsx'));
    if (filename.length !== 0) {
        let question = xlsx.question( join( __dirname, `../public/xlsx/${filename[0]}`) );
        // 调整数据格式
        let quesName = question.shift().ques;
        let quesGist = question.shift().ques;
        question = {
            quesName,
            quesGist,
            quesContent: question
        };
        await addQuestion.addQuestionPlus(question)
            .then(res => {
                let errMsg = '';
                if (res) {
                    errMsg = res.errmsg.split("\"")[1];
                }
                ctx.body = {
                    status: 200,
                    msg: '上传成功',
                    errMsg
                }
            }).catch(err => {
                console.log(err)
            });
    }else {
        ctx.body = {
            status: 400,
            msg: '上传失败，请重试'
        }
    }
};